package com.longcheer.weibo;


import com.longcheer.weibo.vo.Province;
import com.weibo.net.WeiboException;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;


public class WeiboProvider {
    private static final String TAG = "WeiboProvider"; 
    
    public static void saveProvinces(Context context, Map<Integer, Province> provinceMap) {
        SQLiteDatabase db = null;
        
        try {
            db = new DBHelper(context).getWritableDatabase();
            Collection<Province> provinces = provinceMap.values();
            for (Province province : provinces) {
                ContentValues values = new ContentValues();
                values.put("code", "" + province.getCode());
                values.put("json", province.toString());

                db.insert("weibo_province", null, values);
            }
        } catch (SQLException e) {
            Log.e(TAG, e.getMessage(), e);
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }
    
    public static Map<Integer, Province> getProvinces(Context context) {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        
        Map<Integer, Province> provinceMap = new HashMap<Integer, Province>();
        try {
            db = new DBHelper(context).getReadableDatabase();
            cursor = db.query("weibo_province", 
                    new String[]{"json"}, null, 
                    null, null, null, null);
            if (cursor.moveToFirst()) {
                do {
                    String str = cursor.getString(0);
                    Province province = new Province(new JSONObject(str));
                    provinceMap.put(province.getCode(), province);
                } while (cursor.moveToNext());
            }
        } catch (SQLException e) {
            Log.e(TAG, e.getMessage(), e);
        } catch (WeiboException e) {
            Log.e(TAG, e.getMessage(), e);
        } catch (JSONException e) {
            Log.e(TAG, e.getMessage(), e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        
        return provinceMap;
    }
}
